package yxy.game.pm2.command.chibi;

import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ChibiMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.chibi.ChibiModule;

/** 火烧赤壁 火烧赤壁购买次数 */
@MessageType(proto = Command.ChibiBuyTimes, classtype = ChibiMessage.ChibiBuyTimesRequest.class)
public class CMD_ChibiBuyTimes extends Command<ChibiMessage.ChibiBuyTimesRequest> {

	@Override
	public void execute(MessageSource messageSource, ChibiMessage.ChibiBuyTimesRequest request) {
		String playerCode = messageSource.getTag();

		ChibiMessage.ChibiBuyTimesResponse.Builder response = ChibiMessage.ChibiBuyTimesResponse.newBuilder();

		ChibiModule chibiModule = ChibiModule.get(playerCode);
		if (chibiModule.remainBuyTimes() <= 0) {
			send(messageSource, response, Result.ChibiBuyTimeOut);// 已经没有购买次数了
			return;
		}

		Currency cost = Currency.create(CurrencyType.CT_元宝, 0, fomula.火烧赤壁购买花费元宝.intValue());

		try {
			new CurrencyHandle().cost(playerCode, CCReason.火烧赤壁, cost);
		} catch (CurrencyNotEnoughException e) {
			send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
			return;
		}
		chibiModule.setBuytimes(chibiModule.getBuytimes() + 1);
		chibiModule.setTimes(chibiModule.getTimes() - 1);
		chibiModule.set();

		response.setTimes(chibiModule.remainTimes());
		response.setBuytimes(chibiModule.remainBuyTimes());

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ChibiMessage.ChibiBuyTimesResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}